<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>欢迎页面-X-admin2.2</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>-->
    <!--<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>-->
    <!--<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>-->
    <!--[endif]-->

    <script type="text/javascript" src="../../common/js/public.js"></script>
    <script type="text/javascript" src="../../common/js/publicUtils.js"></script>
    <!-- <script type="text/javascript" src="../js/tokenUtils.js"></script>-->
</head>
<body>
<div class="layui-fluid" id="flowDiv" onload="onLoad()">
    <div class="zTreeBackground left" style="float: left;width:300px">
        <div class="titlediv">
            <p style="text-align:right;background-color:white;line-height: 30px">
                组织信息<i class="layui-icon layui-icon-refresh" style="margin-left: 36%" onclick="refreshRoot()"></i>&ensp;&ensp;
            </p>

        </div>
        <div class="searchdiv" >
            <div class="layui-input-inline" style="width:100%">
                <input type="text" id="search" name="keyword" autocomplete="off" class="layui-input" placeholder="请输入名称"/>
                <i class="layui-icon layui-icon-search" style="position: absolute;top:8px;right: 8px;" onclick="searchByName()"></i>
            </div>
        </div>
        <div class="ztreediv" id="ztreediv">
            <div class="ztreeuldiv">
                <ul id="treeStructure" class="ztree"></ul>
            </div>
        </div>
    </div>
    <div class="zTreeBackground right" style="float: left; padding-left:1%;width:70%">
        <table class="layui-hide" id="datatable"></table>
        <script type="text/html" id="toolbar">
        </script>

    </div>
    <div id="gps"></div>
</div>
</body>
<script>
    var table,nodeSelected,zTreeObj,prjState;
    $(function(){
        loadbutton("toolbar");//加载按钮loadbutton(id)，id为button容器id，不传默认为buttongroup
        initTree("#treeStructure");
        prjState=getDic("PrjState");
    })
    window.onload = getContentSize;
    window.onresize = getContentSize;

    /**
     * 页面自适应
     */
    function getContentSize() {
        var wh = document.documentElement.clientHeight;
        var eh = 30;
        ch = (wh - eh) + "px";
        document.getElementById( "flowDiv" ).style.height = ch;
        document.getElementById( "ztreediv" ).style.height = (wh - eh - 50)+"px";
        document.body.style.height = (wh)+"px";
        $(".zTreeBackground.right").css("width",($(document).width()-350)+'px');//自适应表格处理
        $(".search_float_div").css("width",($(document).width()-350)+'px');//自适应表格处理
    }

    var setting = {
        check: {
            //enable: true,
            chkboxType: { "Y": "s", "N": "s" }
        },
        edit:{
            enable: false
        },
        async: {
            enable: true,
            url: publicUrl+"project/getProjectsForTree",
            dataFilter: formatedata,
            headers: {"Authorization":getData("Authorization")},
            autoParam: ["id","type"]
        },
        data: {
            simpleData: {
                enable: true,
                idKey:"id",
                pIdKey:"pid",
                isParent:"parent",
                rootPid:"",
                type:"type"

            },
            key: {
                isParent:"parent",
                url: "xUrl",
                icon:"xIcon",
                level:"orgLevel",
                name:"shortName"
            }
        },
        callback: {
            beforeClick: beforeClick,
            onClick: zTreeOnClick
        }
    };

    /* *
     * @Author bxf
     * @Description 刷新树
     * @Date 11:16 2019/8/28
     * @param null
     * @return
     */
    function refreshRoot(){
        initTree("#treeStructure");
    }

    function searchByName(){
        var search = $("#search").val();
        if(!search){
            return ;
        }
        loadTree("#treeStructure");
    }
    /* *
     * @Author bxf
     * @Description 加载树
     * @Date 14:31 2019/8/28
     * @param null
     * @return
     */
    function loadTree(id){
        $(id).html('');
        publicAjax (null,'orgstation/getProjectsForTree',{"name":$("#search").val(),"stationFlag":2,"type":5},false,null,function(data){
            zTreeObj = $.fn.zTree.init($(id),setting, changeIcon(data.data));
            zTreeObj.expandAll(true);
        })
    }

    function formatedata(treeId,parentNode,responseData) {
        return changeIcon(formatTreeParseData(treeId,parentNode,responseData,null));
    }

    function initTree(id){
        $(id).html('');
        publicAjax(null,"company/getByPersonId",{},false,null,function(data){
            zTreeObj = $.fn.zTree.init($(id),setting, changeIcon(data.data));
            /* console.log(zTreeObj);
             //让第一个父节点展开
             var rootNode_0 = zTreeObj.getNodeByParam('pid',0,null);
             zTreeObj.expandNode(rootNode_0, true, false, false, false);*/
        })
    }

    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）

    function beforeClick(treeId, treeNode, clickFlag) {
        if(treeNode.type!=4){
            layer.msg("请选择项目部",{time:500});
            return false;
        }
    }

    function zTreeOnClick(event, treeId, treeNode, clickFlag) {

        if(treeNode.type === 4){
            nodeSelected = treeNode;
            initTable();
        }
    }

    function setFontCss_ztree(treeId, treeNode) {
        if (treeNode.id == 0) {
            //根节点
            return {color: "#333", "font-weight": "500"};
        } else if (treeNode.isParent == false) {
            //叶子节点
            return (!!treeNode.highlight) ? {color: "#ff0000", "font-weight": "bold"} : {
                color: "#660099",
                "font-weight": "normal"
            };
        } else {
            //父节点
            return (!!treeNode.highlight) ? {color: "#ff0000", "font-weight": "bold"} : {
                color: "#333",
                "font-weight": "normal"
            };
        }
    }

    //获取所有项目用于选择父项目
    function initTable(){
        var cols = [
            [   {
                type:'checkbox',
                width: "5px",
                },
                {
                    type: 'numbers',
                    title: '序号',
                    width: "5%",
                    align: 'center',
                }, {
                field: 'name',
                title: '名称',
                sort: true,
                width: "20%",
                align: 'center'
            }, {
                field: 'shortName',
                title: '简称',
                sort: true,
                width: "15%",
                align: 'center',
            }, {
                field: 'state',
                title: '状态',
                width: "8%",
                templet: function(d) {
                    return prjState.get(d.state+"");
                },
                sort: true,
                align: 'center'
            },{
                field: 'contractCost',
                title: '合同造价',
                sort: true,
                width: "10%",
                align: 'center'
            },{
                field: 'orgName',
                title: '所属项目',
                sort: true,
                width: "15%",
                align: 'center'
            },{
                field: 'beginDate',
                title: '合同开工日期',
                sort: true,
                width: "10%",
                align: 'center'
            },{
                field: 'endDate',
                title: '合同完工日期',
                sort: true,
                width: "10%",
                align: 'center'
            }]
        ]
        var width = $(".left-nav").css("width");
        $(".zTreeBackground.right").css("width",($(document).width()-380)+'px');//自适应表格处理
        $(".search_float_div").css("width",($(document).width()-380)+'px');//自适应搜索div
        layui.use('table', function() {
            table = layui.table;
            table.render({
                elem: '#datatable',
                size:"sm",
                height: 'full-100',
                toolbar: '#toolbar',
                url:publicUrl+'project/getByPid',
                headers: {"Authorization":getData("Authorization")},
                where: {"companyId":nodeSelected.id},
                parseData: function(res){ //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                },
                response: {
                    statusCode: 2000,
                },
                method: 'post',
                cols: cols,
                limit: 20,
                page: true
                /*  page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                      layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'] //自定义分页布局
                  },*/
                /*done: function(){
                    store.get('loginName') != 'Administrator' ? $('img[lay-event="delet"]').addClass('hideNone') : $('img[lay-event="delet"]').removeClass('hideNone')
                }*/
            });
        })
    }

    //初始化添加按钮
    function initAdd(){
        if(!nodeSelected && nodeSelected.type!=4){
            layer.alert("请选择项目部！");
        }
        var iframeWin;
        $("form[id='formTest'] :input").removeAttr("disabled");
        if(typeof (nodeSelected) != "undefined" && nodeSelected != null && nodeSelected != ""){
            var indexAdd = layer.open({
                type: 2,
                title: '新增项目',
                //			maxmin: true,
                shadeClose: false, //点击遮罩关闭层
                area: ['1150px', '700px'],
                content: './addproject.html',
                //content: $("#addpro"),
                btn: ['应用','完成','取消'],
                maxmin: false,
                success: function(layero, index) {
                    iframeWin = layero.find('iframe')[0];
                    iframeWin.contentWindow.inintflag(1,null);
                },
                yes: function(index, layero) {
                    var resultdata = iframeWin.contentWindow.submitcreate('project/insertOrUpdate');
                    index_i1 = '';
                },
                btn2: function(index, layero) {
                    var resultdata = iframeWin.contentWindow.submitcreate('project/insertOrUpdate');
                    index_i1 = indexAdd;
                    return false;
                },
                cancel: function(index, layero) {

                }
            });
        }else{
            layer.alert("请选择组织");
        }
    }
    /* *
     * @Author bxf
     * @Description 导入文件
     * @Date 9:14 2019/9/4
     * @param null
     * @return
     */
    function uploadProject(){
        if(!nodeSelected && nodeSelected.type!=4){
            layself("请选择项目部！");
            return false;
        }
        var iframeWin ;
        layer.open({
            type: 2,
            area: ["500px" , "350px"],
            fix: false,
            //不固定
            maxmin: false,
            shade: 0.3,
            title: "导入项目",
            content: "./uploadproject.html",
            btn: ['关闭'],
            // 弹层外区域关闭
            shadeClose: false,
            yes: false,
            cancel: function(index) {
                return true;
            },
            success: function(layero, index){
                iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.getdisciplineId(nodeSelected);//添加按钮
            }
        });
    }
    /* *
     * @Author bxf
     * @Description 更新数据
     * @Date 8:47 2019/9/4
     * @param null
     * @return
     */
    function initUpdate(){
            var iframeWin,table;
            layui.use('table',function(){
                table = layui.table;
            })
            var nodeForUpdate = table.checkStatus('datatable').data;
            if(nodeForUpdate!=null && typeof (nodeForUpdate) != 'undefined'){
                if(nodeForUpdate.length>1){
                    layer.alert("修改只能选择一个");
                }
                if(nodeForUpdate.length == 1){
                    var indexUpdate = layer.open({
                        type: 2,
                        title: '编辑项目',
                        //			maxmin: true,
                        shadeClose: false, //点击遮罩关闭层
                        area: ['1150px', '700px'],
                        content: './addproject.html',
                        //content: $("#addpro"),
                        btn: ['确定','取消'],
                        maxmin: false,
                        success: function(layero, index) {
                            iframeWin = layero.find('iframe')[0];
                            iframeWin.contentWindow.inintflag(2,nodeForUpdate);
                        },
                        yes: function(index, layero) {
                            index_i = indexUpdate;
                            iframeWin.contentWindow.submitupdate('project/insertOrUpdate');
                        },
                        cancel: function(index, layero) {

                        }
                    });
                }
                if(nodeForUpdate.length==0){
                    layer.alert("请选择要修改的记录");
                }
            }
        }

    //删除按钮
    function initDelete(){
        //获取要删除的点
        var nodeIdForDeleteStr = '';
        var nodeForDelete = table.checkStatus('datatable').data;
        if(typeof(nodeForDelete)!="undefined" && nodeForDelete!=null && nodeForDelete.length>0){

            layer.confirm('确认删除吗？', {
                btn: ['确定','取消'] //按钮
            }, function(index){
                for(var i=0;i<nodeForDelete.length;i++){
                    nodeIdForDeleteStr = nodeIdForDeleteStr + nodeForDelete[i].id + ",";
                }
                publicAjax(null,"project/delete",{"ids":nodeIdForDeleteStr,"orgId":nodeSelected.id},false,null,function (data){
                    var data = {"companyId":nodeSelected.id};
                    reloadTable("datatable",data);
                    layer.close(index);
                })
            }, function(){

            });
        }
    }

    function initMoveTo(){
            var projectForMoveTo = table.checkStatus('datatable').data;
            var iframeWin;
            if(typeof(projectForMoveTo)!="undefined" && projectForMoveTo.length>0) {
                var index = layer.open({
                    type: 2,
                    title: '选择公司',
                    //			maxmin: true,
                    shadeClose: false, //点击遮罩关闭层
                    area: ['430px', '600px'],
                    //			content: '../alert/addProject.html',
                    content: 'projectselecttree.html',
                    btn: ['确定', '取消'],
                    maxmin: true,
                    success: function (layero, index) {
                        iframeWin = layero.find('iframe')[0];
                        iframeWin.contentWindow.inintData(projectForMoveTo);
                    },
                    yes: function (index, layero) {
                        var resultdata = iframeWin.contentWindow.moveTo();//移动
                        var childrenTree = iframeWin.contentWindow.node;
                        if(resultdata==false){
                            return false;
                        }else{
                            if(resultdata && resultdata.code==2000){
                                //刷新原来选中的节点
                                zTreeObj.reAsyncChildNodes(nodeSelected, "refresh");
                                //刷新新选中的节点
                                var nodeSelectedForShow = zTreeObj.getNodeByParam('id',childrenTree.id,null);
                                zTreeObj.reAsyncChildNodes(nodeSelectedForShow, "refresh");
                                var data = {"companyId":nodeSelected.id};
                                reloadTable("datatable",data);
                                delayLoad(function(){
                                    layer.closeAll();
                                })
                            }else{
                                return false;
                            }
                        }

                    },
                    cancel: function (index, layero) {
                    }
                });
            }else{
                layer.alert("请选择要移动的项目");
            }
    }

    function reloadTable(tableId,data){
        table.reload(tableId, { //此处是上文提到的 初始化标识id
            where: data
        });
    }
</script>
</html>